package edu.nf.project.services.storeOperation.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.nf.project.entitys.entity.storeOperation.convention.inspect.SelfInspection;
import edu.nf.project.mappers.storeOperation.convention.SelfInspectionMapper;
import edu.nf.project.services.exception.derivedAnomalies.SelfInspectionException;
import edu.nf.project.services.storeOperation.SelfInspectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.util.Date;
import java.util.List;

/**
 * 自检服务实现类
 */
@Service
public class SelfInspectionServiceImpl implements SelfInspectionService {
    @Autowired
    private SelfInspectionMapper selfInspectionMapper;

    @Value("${upload.path}")
    private String uploadPath;

    @Override
    public Page<SelfInspection> getSelfInspectionList(Page<SelfInspection> page) {
        return selfInspectionMapper.selectPage(page, null);
    }

    @Override
    public SelfInspection getSelfInspectionInfo(Integer siId) {
        SelfInspection selfInspection = selfInspectionMapper.selectById(siId);
        if (selfInspection == null) {
            throw new SelfInspectionException(60001, "自检记录不存在");
        }
        return selfInspection;
    }

    @Override
    @Transactional
    public boolean createSelfInspection(SelfInspection selfInspection) {
        // 设置状态为未完成
        selfInspection.setSiStatus(false);
        return selfInspectionMapper.insert(selfInspection) > 0;
    }

    @Override
    public List<SelfInspection> listSelfInspectionByStoreId(Integer year, Integer month, Integer storeId) {
        LambdaQueryWrapper<SelfInspection> wrapper = new LambdaQueryWrapper<>();
        wrapper.apply("YEAR(si_date) = {0}", year)
                .apply("MONTH(si_date) = {0}", month)
                .eq(SelfInspection::getStoreId, storeId)
                .orderByAsc(SelfInspection::getSiDate);
        return selfInspectionMapper.selectList(wrapper);
    }

    @Override
    public boolean existsByDate(Date date) {
        LambdaQueryWrapper<SelfInspection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SelfInspection::getSiDate, date);
        SelfInspection selfInspection = selfInspectionMapper.selectOne(wrapper);
        return selfInspection != null;
    }

    @Override
    public void updateSelfInspection(SelfInspection selfInspection) {
        selfInspectionMapper.updateById(selfInspection);
    }
}